package com.codebattery.util;

import com.alibaba.fastjson.JSON;
import com.codebattery.config.EsUtilBaseConfig;
import com.codebattery.domain.entity.EsEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
public class EsUtil {

    public static final String INDEX_NAME = "book-index";
    public static String CREATE_INDEX;
    public static RestHighLevelClient restClient = null;
    private static EsUtilBaseConfig config;

    public EsUtil(EsUtilBaseConfig config) {
        this.config = config;
        restClient = new RestHighLevelClient(RestClient.builder(
                new HttpHost(config.getHost(),
                        Integer.valueOf(config.getPort()),
                        config.getScheme())));
    }

    private static String readFileToString(String filePath) {
        File file = new File(filePath);
        log.debug(file.getAbsolutePath());
        try (FileReader reader = new FileReader(file)) {
            BufferedReader bReader = new BufferedReader(reader);
            StringBuilder sb = new StringBuilder();
            String s = "";
            while ((s = bReader.readLine()) != null) {
                sb.append(s + "\n");
            }
            return sb.toString();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return "";
    }

    public void createIndex(String indexName) throws Exception {

        CreateIndexRequest request = new CreateIndexRequest(indexName);
        request.settings(Settings.builder().put("index.number_of_shards", 3).put("index.number_of_replicas", 2));
        request.mapping(indexName, XContentType.JSON);
        CreateIndexResponse res = null;

        res = restClient.indices().create(request, RequestOptions.DEFAULT);

        if (!res.isAcknowledged()) {
            throw new RuntimeException("创建index失败");

        }
    }

    public boolean indexExist(String index) throws Exception {
        GetIndexRequest request = new GetIndexRequest(index);
        request.local(false);
        request.humanReadable(true);
        request.includeDefaults(false);
        return restClient.indices().exists(request, RequestOptions.DEFAULT);
    }

    public IndexResponse insertOrUpdateOne(String index, EsEntity entity) {
        IndexRequest request = new IndexRequest(index);
        request.id(entity.getId());
        request.source(JSON.toJSONString(entity.getData()), XContentType.JSON);
        try {
            log.info("新增或更新索引{}成功, 实体[{}]", index, entity);
            return restClient.index(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public BulkResponse insertBatch(String index, List<EsEntity> list) {
        BulkRequest request = new BulkRequest();
        for (EsEntity item : list) {
            String _json = JSON.toJSONString(item.getData());
            String _id = item.getId();
            IndexRequest indexRequest = new IndexRequest(index).id(_id).source(_json, XContentType.JSON);
            request.add(indexRequest);
        }
        try {
            return restClient.bulk(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public <T> List<T> search(String index, SearchSourceBuilder searchSourceBuilder, Class<T> resultClass) {
        SearchRequest request = new SearchRequest(index);
        request.source(searchSourceBuilder);
        try {
            SearchResponse response = restClient.search(request, RequestOptions.DEFAULT);

            SearchHits hits1 = response.getHits();
            SearchHit[] hits2 = hits1.getHits();
            List<T> retList = new ArrayList<>(hits2.length);
            for (SearchHit hit : hits2) {
                String strJson = hit.getSourceAsString();
                retList.add(JSON.parseObject(strJson, resultClass));
            }
            return retList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public AcknowledgedResponse deleteIndex(String index) {
        try {
            IndicesClient indicesClient = restClient.indices();
            DeleteIndexRequest request = new DeleteIndexRequest(index);
            AcknowledgedResponse response = indicesClient.delete(request, RequestOptions.DEFAULT);
            return response;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public BulkByScrollResponse deleteByQuery(String index, QueryBuilder builder) {
        DeleteByQueryRequest request = new DeleteByQueryRequest(index);
        request.setQuery(builder);
        request.setBatchSize(10000);
        request.setConflicts("proceed");
        try {
            BulkByScrollResponse response = restClient.deleteByQuery(request, RequestOptions.DEFAULT);
            return response;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public <T> BulkResponse deleteBatch(String index, Collection<T> idList) {
        BulkRequest request = new BulkRequest();
        for (T t : idList) {
            request.add(new DeleteRequest(index, t.toString()));
        }
        try {
            BulkResponse response = restClient.bulk(request, RequestOptions.DEFAULT);
            return response;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}